<template>
  <a-modal
    title="批量编辑车位"
    :visible="visible"
    :width="640"
    :mask-closable="false"
    :bodyStyle="{ padding: '40px' }"
    @cancel="hide"
    :footer="null"
  >
    <div class="flex-h-hs-vc">
      <div @click="downloadTemplate" v-yd-loading="downloadParams.loading" class="box">
        <img class="icon" src="~@/assets/images/download.png" />
        <span class="blue">点击下载模板</span>
      </div>
      <div v-yd-loading="uploadParams.loading" class="box" style="width: 320px">
        <img class="icon" src="~@/assets/images/upload.png" />
        <span class="blue">上传文件批量编辑</span>
        <input
          accept=".xls,.xlsx,.csv"
          @change="uploadChange($event)"
          class="file-absolute"
          type="file"
          title="点击上传" />
      </div>
    </div>
  </a-modal>
</template>

<script>
import { importPlaceAPI } from '@/api/place'
import { downloadFile } from '@/utils/util'

export default {
  data () {
    return {
      visible: false,
      downloadParams: {
        loading: false
      },
      uploadParams: {
        loading: false
      }
    }
  },
  methods: {
    open () {
      this.visible = true
    },
    hide () {
      this.visible = false
    },
    /** @name 下载模版 **/
    async downloadTemplate () {
      this.downloadParams.loading = true
      try {
        await downloadFile(`/place/download`, '车位导入模版.xlsx')
      } catch (error) {
        this.$message.error('下载异常，请联系管理人员')
        this.downloadParams.loading = false
      }
      this.downloadParams.loading = false
    },
    /** @name 上传节点 **/
    uploadChange (e) {
      const input = e.target
      if (!input.files.length) return this.$message.error('请点击上传相关文件')
      const file = e.target.files[0]
      const fileFormData = new FormData()
      fileFormData.append('file', file)
      this.uploadParams.loading = true
      importPlaceAPI(fileFormData).then(res => {
        this.$confirm({
          title: '上传成功',
          icon: h => h('a-icon', {
            props: {
              type: 'check-circle',
              theme: 'filled'
            }
          }),
          content: `当前上传文件中共有${res.data}条数据`,
          onOk: () => {
            this.$emit('batchImport', res.data)
            this.hide()
          }
        })
      }).finally(() => {
        input.value = ''
        this.uploadParams.loading = false
      })
    }
  }
}
</script>

<style scoped>
.box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  background-color: #F3F7FD;
  border: 1px solid #D8D8D8;
  color: #1890FF;
  font-size: 16px;
  cursor: pointer;
  position: relative;
}
.icon {
  width: 40px;
  height: 38px;
  margin-bottom: 10px;
}
.blue {
  color: #1890FF;
}
</style>

<style>
.anticon-check-circle {
  color: #52c41a !important;
}
</style>
